const babel = require("@babel/core")
const { minify } = require("terser")
const { generateRandomString } = require("./utils.js")
const methodsRename = function () {
  return {
    name: "ast-transform", // not required
    visitor: {
      ObjectExpression(path) {
        if (
          path.parent.type === "ObjectProperty" &&
          path.parent.key.name === "methods"
        ) {
          path.node.properties.forEach((item) => {
            item.key.name = `_${generateRandomString()}`
          })
        }
      },
    },
  }
}
const trannformJS = async (script) => {
  const { code: scriptFormat } = babel.transformSync(script, {
    sourceType: "module",
    configFile: false,
    plugins: [methodsRename()],
  })
  const { code: uglyCode } = await minify(scriptFormat)
  return uglyCode
}
module.exports = trannformJS
